<?php

function plant_measure_add_page() {
    return drupal_get_form('plant_measure_edit_form');
}

function plant_measure_edit_page($id) {
    return drupal_get_form('plant_measure_edit_form', $id);
}

function plant_measure_edit_form($form, &$form_state) {
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {
        $form['#farmer'] = $form_state['farmer'];
    }

    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('plant_measure', 'plant_measure_id', $id);
        if (empty($record)) {
            drupal_set_message(t('田间测产数据不存在！'), 'status', FALSE);
            return $form;
        }
        $form['#plant_measure_id'] = $id;
    }

    // 判断用户角色
    if(!nonghua_user_access('plant_measure', 'view', $id, !empty($record) ? $record->author_uid:0, $record->farmer_id) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    insert_special_activities($form,$form_state,isset($record) && !empty($record)?$record:'');

    // 农户
    _insert_farmer_select_info($form, $form_state, $record);
    // 日期
    $form['measure_date'] = array(
        '#title' => '测产日期',
        '#type' => 'metercomm_date',
        '#default_value' =>  _date_db_2_form(!empty($record) ? $record->measure_date : ''),
        '#required' => TRUE,
    );
    // 作物
    $plant_options[''] = '请选作物';
    $query = db_select('plant','P');
    $query->fields('P',array('plant_id','plant_name'));
    $plant_info = $query->execute()->fetchAll();

    foreach ($plant_info as $k => $v ) {
        $plant_options[$v->plant_id] = $v->plant_name;
    }
//    $form['plant'] = array(
//        '#title' => '作物',
//        '#type' => 'select',
//        '#validated' => TRUE,
//        '#required' => TRUE,
//        '#options' => $plant_options,
//        '#default_value' => !empty($record) ? $record->plant_id:'',
//    );
    $form['plant'] = array_merge( _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:''),
                                ['#ajax' => array('callback' => 'plant_select_callback',
                                                    'wrapper' => 'plant_measure_item_wrapper',
                                                    'effect' => 'fade'),
                                    '#disabled' => !empty($record)? TRUE : FALSE]);

    // 测产项目
    $form['plant_measure_item']['start']['#markup'] = '<div id="plant_measure_item_wrapper"><table class="plant-measure-table"><tr><th>项目</th><th>撒可富</th><th>对照</th></tr>';

    if (!empty($record)) {
        // 取得测产值，在编辑状态下
        $query = db_select('plant_measure', 'PM');
        $query->join('plant_measure_item', 'PMI', 'PM.plant_id = PMI.plant_id');
        $query->leftJoin('plant_measure_value', 'PMV', 'PMI.plant_measure_item_id = PMV.plant_measure_item_id AND PM.plant_measure_id = PMV.plant_measure_id');
        $query->condition('PM.plant_measure_id', $id, '=');
        $query->Fields('PMI',array('plant_measure_item_id','plant_measure_item_name'));
        $query->Fields('PMV',array('plant_measure_column_name','value'));
        $query->orderBy('PMI.plant_measure_item_id');
        $query->orderBy('PMV.plant_measure_column_name', 'DESC');
        $result = $query->execute();

        $last_plant_measure_item_id = -1;
        foreach ($result as $row) {
            if ($last_plant_measure_item_id != $row->plant_measure_item_id) {
                $last_plant_measure_item_id = $row->plant_measure_item_id;
                $newline = true;
            } else {
                $newline = false;
            }

            if ($newline) {
                // 测产项目名称
                $form['plant_measure_item']['measure-item-' . $row->plant_measure_item_id . '-title'] = array('#markup' => $row->plant_measure_item_name, '#prefix' => '<tr><td>', '#suffix' => '</td>');
            }

            if ($row->plant_measure_column_name == 'sacf') {
                // 撒可富
                $form['plant_measure_item']['measure-item-' . $row->plant_measure_item_id . '-sacf'] = array(
                    '#type' => 'textfield',
                    '#prefix' => '<td>', '#suffix' => '</td>',
                    '#default_value' => $row->value,
                );
            } else {
                // 对照
                $form['plant_measure_item']['measure-item-' . $row->plant_measure_item_id . '-compare'] = array(
                    '#type' => 'textfield',
                    '#prefix' => '<td>', '#suffix' => '</td></tr>',
                    '#default_value' => $row->value,
                );
            }
        }
    } else {
        // 取得测产项目，在添加状态下
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false);
        $plant_measure_items = db_select('plant_measure_item', 'T')
            -> fields('T')
            -> condition('T.plant_id', (!empty($record) ? $record->plant_id :$plant_id), '=')
            -> execute()
            -> fetchAll();

        foreach ($plant_measure_items as $row) {
            // 测产项目名称
            $form['plant_measure_item']['measure-item-' . $row->plant_measure_item_id . '-title'] = array('#markup' => $row->plant_measure_item_name, '#prefix' => '<tr><td>', '#suffix' => '</td>');
            // 撒可富
            $form['plant_measure_item']['measure-item-' . $row->plant_measure_item_id . '-sacf'] = array(
                '#type' => 'textfield',
                '#prefix' => '<td>', '#suffix' => '</td>',
            );
            // 对照
            $form['plant_measure_item']['measure-item-' . $row->plant_measure_item_id . '-compare'] = array(
                '#type' => 'textfield',
                '#prefix' => '<td>', '#suffix' => '</td></tr>',
            );
        }
    }

    $form['plant_measure_item']['end']['#markup'] = '</table></div>';

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($record) ? '修改' : '提交',
        '#access' =>  nonghua_user_access('plant_measure', 'edit', $id, !empty($record) ? $record->author_uid:0, $record->farmer_id) ,
    );

    return $form;
}

function plant_measure_edit_form_validate($form, &$form_state) {
    if($form_state['values']['plant'] ){
        $plant_measure_items = db_select('plant_measure_item', 'T')
            -> fields('T')
            -> condition('T.plant_id', get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false), '=')
            -> execute()
            -> fetchAll();
        if(empty($plant_measure_items)){
            form_set_error('plant', "请先填写与该农作物相关的测产项目！");
        }
    }
    if (empty($form_state['values']['farmer_id'])) {
        form_set_error('farmer_name', "农户必选");
    }
    if (empty($form_state['values']['plant'])) {
        form_set_error('plant', "农作物必选");
    }
    if(!empty($form_state['values']['plant'])){
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false);
        if(empty($plant_id)){
            form_set_error('plant', "作物信息不存在！");
        }
    }

    $reg = '/^\d{1,8}(.\d{0,2})?$/';
    foreach ($form_state['values'] as $key => $value) {
        if (strpos($key, 'measure-item-') === 0) {
            if (!empty($value) && !preg_match($reg, $value)) {
                form_set_error($key, "格式错误");
            }
        }
    }
}

function plant_measure_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;

    $transaction = db_transaction();
    $timestamp = time();
    try {
        if (empty($id)) {
            // 插入plant_measure
            $nid = db_insert('plant_measure')
                ->fields(array(
                    'farmer_id' => $form_state['values']['farmer_id'],
                    'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                    'date' => _date_form_2_db($form_state['values']['measure_date']),
                    'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                    'created' => $timestamp,
                    'author_uid' => $user->uid,
                    'timestamp' => $timestamp))
                ->execute();

            // 插入测产值表
            foreach ($form_state['values'] as $key => $value) {
                if (strpos($key, 'measure-item-') === 0) {
                    $key_array = explode('-',$key);
                    db_insert('plant_measure_value')
                        ->fields(array(
                            'plant_measure_id' => $nid,
                            'plant_measure_item_id' => $key_array[2],
                            'plant_measure_column_name' => $key_array[3],
                            'value' => empty($value) ? null : $value,
                            'created' => $timestamp,
                            'author_uid' => $user->uid,
                            'timestamp' => $timestamp))
                        ->execute();
                }
            }

            if ($nid > 0) {
                drupal_set_message(t('添加成功！'), 'status', FALSE);
            }
            if(!empty($_GET['farmer_id'])){
                drupal_goto('plant_measure/add/'.$nid,array('query' => array('farmer_id' => $_GET['farmer_id'])));
            }
            if(!empty($_GET['addr_id'])){
                drupal_goto('plant_measure/list',array('query' => array('addr_id' => $_GET['addr_id'])));
            }
        } else {
            $nid = db_update('plant_measure')
                ->fields(array(
                    'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                    'author_uid' => $user->uid,
                    'timestamp' => $timestamp))
                ->condition('plant_measure_id', $id, '=')
                ->execute();

            // 更新测产值表
            foreach ($form_state['values'] as $key => $value) {
                if (strpos($key, 'measure-item-') === 0) {
                    $key_array = explode('-',$key);
                    db_update('plant_measure_value')
                        ->fields(array(
                            'value' => empty($value) ? null : $value,
                            'author_uid' => $user->uid,
                            'timestamp' => $timestamp))
                        ->condition('plant_measure_id', $id, '=')
                        ->condition('plant_measure_item_id', $key_array[2], '=')
                        ->condition('plant_measure_column_name', $key_array[3], '=')
                        ->execute();
                }
            }

            if ($nid > 0) {
                drupal_set_message(t('修改成功！'), 'status', FALSE);
            }
            if(!empty($_GET['farmer_id'])){
                drupal_goto('plant_measure/list',array('query' => array('farmer_id' => $_GET['farmer_id'])));
            }
            if(!empty($_GET['addr_id'])){
                drupal_goto('plant_measure/list',array('query' => array('addr_id' => $_GET['addr_id'])));
            }
        }
    } catch (Exception $e){
        $transaction->rollback();
        watchdog_exception('user', $e);
        drupal_set_message(t('操作失败！').$e->getMessage(), 'status', FALSE);
    }
}

/**
 * Ajax callback adding dynamic form elements
 */
function plant_select_callback($form, $form_state) {
    return $form['plant_measure_item'];
}